package main

import (
	"fmt"
	"git.multiverse.io/eventkit/dxc-server/config"
	"git.multiverse.io/eventkit/dxc-server/config/factory"
	"git.multiverse.io/eventkit/dxc-server/job"
	"git.multiverse.io/eventkit/dxc-server/mgmt/metrics"
	"git.multiverse.io/eventkit/dxc-server/routers"
	"git.multiverse.io/eventkit/kit/handler"
	"git.multiverse.io/eventkit/kit/handler/heartbeat"
	"git.multiverse.io/framework/log"
	"net/http"
	_ "net/http/pprof"
	"os"
	"os/signal"
	"syscall"
)

var (
	AppName  = "Dxc"
	confPath = "conf/app.toml"
)

func Init() error {
	// init config
	if err := factory.InitDxcServerConfig(confPath); err != nil {
		return err
	}

	// init log
	log.Init(config.Cfg.GenLogConfig())

	// start transaction recover job
	job.StartTransactionRecoverJob()

	// load transaction info from redis
	if err := job.StartSyncUnfinishedRecordsFromStorageJob(); err != nil {
		log.Errorsf("StartSyncUnfinishedRecordsFromStorageJob: load transaction info from redis failed err=%v", err)
		return err
	}

	// start expireTime recover job
	job.StartTimeExpiredRecordsRecoverJob()

	// start redundancy abnormal transaction job
	job.StartRedundancyAbnormalTransactionJob()

	// start handler
	if err := handler.Start(routers.InitHandlerRouters, config.Cfg.GenInitConfig()...); nil != err {
		log.Errorsf("failed to init event receiver, error=%++v", err)
		return err
	}

	// start do metrics
	if err := metrics.StartDTSMetricsReport(); nil != err {
		log.Errorsf("Start DTS metrics report failed, error=%++v", err)
		return err
	}

	// start heartbeat
	if err := heartbeat.StartHeartbeat(config.Cfg.Heartbeat.TopicName, config.Cfg.Heartbeat.IntervalSeconds); nil != err {
		return err
	}
	return nil
}

func main() {
	if err := Init(); nil != err {
		panic(fmt.Sprintf("failed to start %s, error=%s", AppName, err))
	}

	http.ListenAndServe("0.0.0.0:7070", nil)
	signals := make(chan os.Signal, 1)
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
	quit := <-signals
	log.Infosf("Received signal %s and exist", quit.String())

	return
}
